// 存储顶部导航栏的显示内容

import {defineStore} from "pinia";
export const useNavStore = defineStore("nav", {
	state: () => {
		// 顶部导航栏显示内容
		return {
			nav: [{name: '首页', path: '/', index: 0}],
			collapse: false,
			tabs: [{name: '首页', path: '/', title: '首页'}],
			currentTab: {
				name: '首页',
				path: '/',
				title: '首页'
			}
		}
	},
	actions: {
		addNav(nav) {
			if (nav.name === "首页") {
				this.nav = [{name: '首页', path: '/', index: 0}]
				return;
			}
			nav.index = this.nav.length
			if (this.nav.length > 1) {
				this.nav[this.nav.length - 1] = nav
			} else {
				this.nav.push(nav)
			}
		},
		setCollapse() {
			this.collapse = !this.collapse
		},
		// 添加tab
		addTab(tab) {
			this.currentTab = tab
			// 判断是否已经存在
			for (let i = 0; i < this.tabs.length; i++) {
				if (this.tabs[i].name === tab.name) {
					return;
				}
			}
			this.tabs.push(tab)
		},
		// 删除tab
		removeTab(tabName) {
			this.tabs = this.tabs.filter(item => item.name !== tabName);
			if (this.tabs.length === 0) {
				this.tabs.push({name: '首页', path: '/', title: '首页'})
			}
			this.currentTab = this.tabs[this.tabs.length - 1]
			this.addNav({
				name: this.currentTab.name,
				path: this.currentTab.path
			})
		},
		setCurrentTab(tab) {
			this.tabs.forEach(item => {
				if (item.name === tab) {
					this.currentTab = item
				}
			})
			this.addNav({
				name: this.currentTab.name,
				path: this.currentTab.path
			})
		}
	},
	persist: {
		enabled: true,
		strategies: [
			{
				key: "nav",
				paths: ["nav", "tabs", 'currentTab']
			}
		]
	}
})